package com.mike.service.impl;

import com.mike.common.Const;
import com.mike.common.ServerResponse;
import com.mike.dao.UserMapper;
import com.mike.pojo.User;
import com.mike.service.IUserService;

import com.mike.util.MD5EncodeUtil;
import com.mike.util.TokenCache;
import com.sun.corba.se.spi.activation.Server;
import com.sun.corba.se.spi.orb.ParserData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;


/**
 * Created by HP on 2018/2/28.
 */

@Service("userService")
public class UserServiceImpl implements IUserService{

    @Autowired
    private UserMapper userMapper;




    @Override
    public ServerResponse<User> login(String username, String password) {
        System.err.println("进入方法");
        //验证用户名是否存在，不存在，返回错误信息
        int resultCount = userMapper.checkUsername(username);
        if(resultCount == 0){
            return ServerResponse.createErrorMessageResponse("用户名不存在");

        }
        //todo 对password进行md5密码处理
        //登录验证
        System.err.println("要登录了");
        User user = userMapper.login(username,password);
        System.err.println("出来了");
        if(user == null){
            //密码错误的话进入这里
            return ServerResponse.createErrorMessageResponse("密码不正确");
        }

        //走到这里就是登录成功，返回数据不应该有密码，因此对密码进行加密处理
        user.setPassword("");
        return ServerResponse.createSuccessResponse("登录成功",user);
    }

    @Override
    public ServerResponse<String> register(User user) {
        System.err.println("进入方法");
        //1-校验用户名是否存在
       ServerResponse valiResponse = this.checkValid(user.getUsername(),Const.ValiType.USERNAME);
        //2-校验email是否存在
        valiResponse = this.checkValid(user.getEmail(), Const.ValiType.EMAIL);
        if(!valiResponse.isSuccess()){
            return ServerResponse.createErrorMessageResponse("E-Mail邮箱已存在");

        }

        System.err.println("用户名和email都没有问题");
        //3-设置用户默认限权为用户限权（user和ADMIN限权需要定义常量）
        user.setRole(Const.Role.ROLE_USER);
        System.err.println(user.getRole());
        //4-md5密码加密
        user.setPassword(MD5EncodeUtil.encodeMD5(user.getPassword()));

        System.err.println("要执行注册方法了！！！！");
        System.err.println(user.toString());
        int resultCount = userMapper.insert(user);
        System.err.println("执行完毕");
        if(resultCount == 0 ){
            ServerResponse.createErrorMessageResponse("注册失败");

        }
        return ServerResponse.createSuccessMessageResponse("注册成功");
    }

    @Override
    public ServerResponse<String> checkValid(String str, String type) {
        if(StringUtils.isNotBlank(type)){
            if(Const.ValiType.USERNAME.equals(type)){
                int resultCount = userMapper.checkUsername(str);
                if(resultCount > 0){
                    return ServerResponse.createErrorMessageResponse("用户名已存在");
                }

            }
            if(Const.ValiType.EMAIL.equals(type)){
                int resultCount = userMapper.checkEmail(str);
                if(resultCount >0){
                    return ServerResponse.createErrorMessageResponse("e-mail已存在");

                }
            }
        }else{
            return ServerResponse.createErrorMessageResponse("参数类型错误！只能选择用户名或email....");

        }
        return ServerResponse.createSuccessResponse("用户名/Email可以用，效验成功");
    }

    @Override
    public ServerResponse<String> getQuestionByUsername(String username) {
        //1-验证用户名是否存在
        ServerResponse validResponse = this.checkValid(username,Const.ValiType.USERNAME);
        if (validResponse.isSuccess()) {
            return ServerResponse.createErrorMessageResponse("用户名不存在");
        }
        String question  = userMapper.selectQuestionByUsername(username);
        if(StringUtils.isNotBlank(question)){
            return ServerResponse.createSuccessResponse(question);
        }

        return ServerResponse.createErrorMessageResponse("该用户没有设置找回密码的问题");
    }

    @Override
    public ServerResponse<String> CheckAnswer(String username, String question, String answer) {
        return null;
    }

    @Override
    public ServerResponse<String> checkAnswer(String username, String question, String answer){
        int resultCount = userMapper.checkAnswer(username,question,answer);
        if(resultCount >0){
            //此时，用户提交的答案是正确的，首先用过UUID算法生成唯一的token值
            String forgetToken = UUID.randomUUID().toString();
            //通过GUAVA的缓存放到该token令牌
            TokenCache.setKey("token_"+username,forgetToken);
            //将token令牌存入serverResponse进行返回
            return ServerResponse.createSuccessResponse(forgetToken);
        }
        return ServerResponse.createErrorMessageResponse("预设问题回单错误，你无权修改密码");
    }

    @Override
    public ServerResponse<String> forgetResetPassword(String username, String passwordNew, String forgetToken) {
        //1-校验令牌是否存在
        if(StringUtils.isBlank(forgetToken)){
            return ServerResponse.createErrorMessageResponse("参数错误，需要传递Token令牌");

        }
        //2-校验用户名是否为空，如果username不存在，则直接返回错误信息，否则token_就可以获得forgetToken,存在安全隐患
        ServerResponse validResponse = this.checkValid(username, Const.ValiType.USERNAME);
        if(validResponse.isSuccess()){
            return ServerResponse.createErrorMessageResponse("用户名不存在");

        }
        //3-从guava缓存中获取token令牌进行非空校验
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX +username);
        if(StringUtils.isBlank(token)){
            ServerResponse.createErrorMessageResponse("Token无效或者已过期");
        }
        //4-比前端创来的token与缓存中的token值是否一致，应用StringUtils进行equals比较,增强代码健壮性和安全性
        if(StringUtils.equals(token,forgetToken)){
            //md5密码加密
            String md5Password = MD5EncodeUtil.encodeMD5(passwordNew);
            //修改密码
            int rowCount = userMapper.updatePasswordByUsername(username,md5Password);
            if(rowCount > 0){
                return  ServerResponse.createSuccessMessageResponse("密码修改成功");

            }
            else{
                ServerResponse.createErrorMessageResponse("Token无效，请重新获取");

            }
            return ServerResponse.createErrorMessageResponse("修改密码失败");
        }
        return null;
    }

    @Override
    public ServerResponse<String> resetPassword(String passwordOld, String passwordNew, User user) {
        //验证旧密码
        int resultCount = userMapper.checkPassword(MD5EncodeUtil.encodeMD5(passwordOld),user.getId());
        if(resultCount == 0){
            return ServerResponse.createErrorMessageResponse("旧密码错误，请重新输入");

        }
        //更改密码
        user.setPassword(MD5EncodeUtil.encodeMD5(passwordNew));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount > 0){
            return ServerResponse.createErrorMessageResponse("更新密码失败");
        }
        return null;
    }

    @Override
    public ServerResponse<User> updateInformation(User user) {
        /**
         * 业务逻辑要求如下
         * 1-不允许修改username
         * 当email有更新是，校验要跟新email信息不能是其他用户已经注册的email地址
         */
        int resultCount = userMapper.checkEmailByUserId(user.getEmail(),user.getId());
        if(resultCount > 0){
            return ServerResponse.createErrorMessageResponse("Email已被其他用户使用，请重新输入");
        }
        //吧更新写入到对象中
        User updateUser = new User();
        updateUser.setUsername(user.getUsername());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());
        //update
        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if(updateCount > 0){
            return ServerResponse.createSuccessResponse("更新个人信息成功！",updateUser);

        }

        return ServerResponse.createErrorMessageResponse("更新个人信息失败");
    }

    @Override
    public ServerResponse<User> getInformation(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null){
            return ServerResponse.createErrorMessageResponse("找不到当前用户");

        }
        //置空密码
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createSuccessResponse(user);
    }

    @Override
    public ServerResponse checkAdminRole(User user) {
        if(user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN){
            return ServerResponse.createSuccessResponse();
        }
        return ServerResponse.createErrorResponse();
    }

    public static boolean isNotBlank(final CharSequence cs){
        return isNotBlank(cs);
    }



}
